<template>
    <!-- 左侧菜单栏 -->
    <div class="left-menu">
        <div class="entity-types">
            <div class="head-img">
                <el-icon style="float: left;">
                    <DArrowRight />
                </el-icon>
                <div>关系类</div>
            </div>
            <div class="button">
                <button>定义样例</button>
                <button @click="triggerFileUpload">导入定义</button>
                <input type="file" ref="fileInput" @change="handleFileUpload" accept=".xlsx" style="display: none;" />
            </div>
            <div class="entity-type-list">
                <div v-for="relation in relations" :key="relation.id" class="entity-type-item" :style="relation.style">
                    <div class="entity-info">
                        <span>({{ relation.sourceText }},{{ relation.text }},{{ relation.targetText }})</span>
                        <span v-if="relation.markedCount !== undefined" class="entity-marked-count">{{
                            relation.markedCount }}个</span>
                    </div>
                    <div class="entity-actions">
                        <button @click="editRelation(relation)" title="编辑关系类">✏️</button>
                        <button @click="deleteRelation(relation)" title="删除关系类">🗑️</button>
                    </div>
                </div>
                <div v-if="relations.length === 0" class="entity-type-item">
                    暂无关系类数据
                </div>
            </div>
            <div class="button">
                <button @click="showAddRelationDialog">添加关系类</button>
                <button @click="exportDefinition">导出定义</button>
            </div>
        </div>

        <div class="entity-instances">
            <div class="head-img">
                <el-icon style="float: left; margin-left: 5px;">
                    <DArrowLeft />
                </el-icon>
                <div>关系实例</div>
            </div>
            <div class="entity-instance-list">
                <template v-if="relationInstances.length > 0">
                    <div v-for="(instance, index) in relationInstances" :key="index" class="relation-instance-item"
                        :style="instance.style">
                        <div class="relation-content">
                            <span class="source-entity">{{ instance.sourceText }}</span>
                            <span class="relation-arrow">→</span>
                            <span class="relation-name">{{ instance.relationText }}</span>
                            <span class="relation-arrow">→</span>
                            <span class="target-entity">{{ instance.targetText }}</span>
                        </div>
                    </div>
                </template>
                <div v-else class="no-data">
                    暂无关系实例数据
                </div>
            </div>
        </div>
    </div>
    <!-- 编辑弹出框 -->
    <div v-if="dialogVisible" class="dialog">
        <div class="dialog-content">
            <h3>编辑关系定义</h3>
            <label>ID: <input type="text" v-model="currentRelation.id" disabled></label>
            <label>名称: <input type="text" v-model="currentRelation.text"></label>
            <label>源实体:
                <select v-model="currentRelation.source">
                    <option value="">请选择</option>
                    <option v-for="entity in entities" :key="entity.id" :value="entity.id">
                        {{ entity.text }}
                    </option>
                </select>
            </label>
            <label>目标实体:
                <select v-model="currentRelation.target">
                    <option value="">请选择</option>
                    <option v-for="entity in entities" :key="entity.id" :value="entity.id">
                        {{ entity.text }}
                    </option>
                </select>
            </label>
            <label>描述: <input type="text" v-model="currentRelation.description"></label>
            <label>路径: <input type="text" v-model="currentRelation.path"></label>
            <div class="dialog-footer">
                <button @click="dialogVisible = false">取消</button>
                <button @click="saveRelation">确定</button>
            </div>
        </div>
    </div>

    <!-- 删除确认弹出框 -->
    <div v-if="deleteDialogVisible" class="dialog">
        <div class="dialog-content-delete">
            <h3 style="text-align: left;">删除关系类</h3>
            <p>确定要删除关系类 "({{ relationToDelete?.sourceText }},{{ relationToDelete?.text }},{{
                relationToDelete?.targetText }})" 吗？</p>
            <div class="dialog-footer">
                <button @click="deleteDialogVisible = false">取消</button>
                <button @click="confirmDelete">确定</button>
            </div>
        </div>
    </div>

    <!-- 添加关系对话框 -->
    <AddRelationDialog v-model="addRelationDialogVisible" @confirm="handleAddRelation" />
</template>
<style scoped>
.left-menu {
    display: flex;
    flex-direction: column;
    width: 290px;
    height: 620px;
    background-color: #f1f1f1;
    margin: 20px;

}

.entity-types {
    padding: 10px;
    display: flex;
    flex-direction: column;
    height: 250px;
    margin-bottom: 10px;
    background-color: #ffffff;
    border-radius: 10px;
}

.entity-instances {
    padding: 10px;
    height: 500px;
    background-color: #ffffff;
    margin-top: 10px;
    border-radius: 10px;
}

.head-img {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.head-img div {
    object-fit: contain;
    margin-left: 5px;
    float: left;
    margin-bottom: 2px;
}

.button button {
    font-size: small;
    float: left;
    width: 100px;
}

.entity-type-list {
    height: 150px;
    /* 设置固定高度 */
    overflow-y: auto;
    /* 启用垂直滚动 */
    margin: 5px 0;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

.entity-type-item {
    margin: 5px 0;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
}

.entity-info {
    flex-grow: 1;
}

.entity-marked-count {
    display: inline-block;
    background-color: #409eff;
    color: white;
    border-radius: 10px;
    padding: 2px 6px;
    font-size: 0.8em;
    margin-left: 5px;
}

.entity-actions {
    display: flex;
    gap: 5px;
}

.entity-relation-info {
    display: flex;
    align-items: center;
    font-size: 0.85em;
    margin-top: 4px;
    color: #555;
}

.relation-entity {
    padding: 2px 5px;
    background-color: rgba(0, 0, 0, 0.05);
    border-radius: 3px;
}

.relation-arrow {
    margin: 0 5px;
    font-weight: bold;
}

.dialog {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.dialog-content {
    background-color: #fff;
    padding: 0;
    border-radius: 8px;
    width: 800px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.dialog-content h3 {
    margin: 0;
    margin-left: 10px;
    padding: 15px 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #ffffff;
    font-size: 16px;
    color: #000000;
    text-align: left;
}

.dialog-content label {
    display: flex;
    align-items: center;
    padding: 10px 20px;
    border-bottom: 1px solid #f0f0f0;
}

.dialog-content label:last-of-type {
    border-bottom: none;
}

.dialog-content label input {
    flex: 1;
    margin-left: 10px;
    padding: 8px;
    border: 1px solid #f0f0f0;
    border-radius: 4px;
}

.dialog-content label input:disabled {
    background-color: #ffffff;
    color: #999;
    cursor: not-allowed;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    padding: 15px 20px;
    background-color: #ffffff;
    border-top: 1px solid #ffffff;
    border-radius: 0 0 8px 8px;
}

.dialog-footer button {
    margin-left: 10px;
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.dialog-footer button:first-child {
    background-color: #f0f0f0;
    color: #333;
}

.dialog-footer button:last-child {
    background-color: #409eff;
    color: white;
}

.dialog-content-delete {
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    width: 400px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.dialog-content-delete h3 {
    margin: 0 0 15px 0;
    font-size: 16px;
    color: #333;
}

.dialog-content-delete p {
    margin: 0 0 20px 0;
    color: #666;
}

.entity-instance-list {
    height: calc(100% - 250)px;
    overflow-y: auto;
    border: 1px solid #eee;
    border-radius: 5px;
    padding: 10px;
    margin-top: 10px;
}

.relation-instance-item {
    padding: 10px;
    margin-bottom: 8px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    transition: all 0.3s ease;
    display: flex;
    flex-direction: column;
}

.relation-instance-item:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    opacity: 0.9;
}

.relation-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
    margin-bottom: 4px;
}

.source-entity,
.target-entity {
    padding: 2px 6px;
    background-color: rgba(255, 255, 255, 0.7);
    border-radius: 3px;
    font-size: 14px;
}

.relation-name {
    color: #333;
    font-weight: 500;
    background-color: rgba(255, 255, 255, 0.7);
    padding: 2px 6px;
    border-radius: 3px;
}

.instance-actions {
    margin-left: auto;
}

.instance-actions button {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 16px;
    padding: 2px 5px;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.7);
}

.no-data {
    text-align: center;
    color: #999;
    padding: 20px;
}
</style>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { DArrowRight, DArrowLeft } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import * as XLSX from 'xlsx';
import AddRelationDialog from './AddRelationDialog.vue';

const fileInput = ref(null);
const relations = ref([]);
const dialogVisible = ref(false);
const deleteDialogVisible = ref(false);
const relationToDelete = ref(null);
const currentRelation = ref({});
const addRelationDialogVisible = ref(false);
const entities = ref([]);
const relationInstances = ref([]);

// 在组件初始化时设置全局变量
// 设置全局方法，供TinyMCE编辑器调用更新标记数量
window.updateRelationMarkedCount = updateRelationMarkedCount;
// 在组件初始化时从localStorage加载关系数据和实体数据
onMounted(() => {
    loadRelationsFromStorage();
    loadEntitiesFromStorage();

    // 加载关系实例数据
    const storedRelations = localStorage.getItem('relationsData');
    if (storedRelations) {
        try {
            const parsedData = JSON.parse(storedRelations);
            // 确保先加载关系类数据，再更新关系实例
            setTimeout(() => {
                updateRelationInstances(parsedData);
            }, 100);
        } catch (error) {
            console.error('初始化关系实例数据失败:', error);
        }
    }
});

// 从localStorage加载实体数据
function loadEntitiesFromStorage() {
    try {
        const storedEntities = localStorage.getItem('entities');
        if (storedEntities) {
            entities.value = JSON.parse(storedEntities);
            console.log('从本地存储加载了', entities.value.length, '个实体用于关系选择');
        }
    } catch (error) {
        console.error('从本地存储加载实体失败:', error);
    }
}

// 更新关系标记数量
function updateRelationMarkedCount(relationCounts, relationTexts = {}, checkedStatus = {}) {
    console.log('更新关系标记数量', relationCounts, relationTexts);
    // 创建一个新数组来存储更新后的关系，以确保Vue能够检测到变化
    const updatedRelations = relations.value.map(relation => {
        const updatedRelation = { ...relation };
        if (relationCounts[relation.id]) {
            updatedRelation.markedCount = relationCounts[relation.id];
            // 更新关系的标注文本内容
            if (relationTexts[relation.id] && relationTexts[relation.id].length > 0) {
                // 存储完整的标注文本数组
                updatedRelation.annotatedTexts = [...relationTexts[relation.id]];
                // 更新检查状态
                if (checkedStatus[relation.id]) {
                    updatedRelation.checkedStatus = [...checkedStatus[relation.id]];
                }
            }
        } else {
            updatedRelation.markedCount = 0;
            updatedRelation.annotatedTexts = [];
            updatedRelation.checkedStatus = [];
        }
        // 设置总数，如果没有则默认为0
        updatedRelation.totalCount = updatedRelation.totalCount || updatedRelation.markedCount || 0;
        return updatedRelation;
    });

    // 替换整个数组以确保Vue能够检测到变化
    relations.value = updatedRelations;
    console.log('更新后的关系列表:', relations.value);
    // 更新全局关系列表，确保TinyMCE编辑器使用最新数据
    window.relations = relations.value;
    // 保存更新后的关系数据到本地存储
    saveRelationsToStorage();
}

// 从localStorage加载关系数据
function loadRelationsFromStorage() {
    try {
        const storedRelations = localStorage.getItem('relations');
        if (storedRelations) {
            relations.value = JSON.parse(storedRelations);
            // 设置全局关系列表，供TinyMCE编辑器使用
            window.relations = relations.value;
            console.log('全局关系列表:', window.relations);
            console.log('从本地存储加载了', relations.value.length, '个关系');
        }
    } catch (error) {
        console.error('从本地存储加载关系失败:', error);
    }
}

// 保存关系数据到localStorage
function saveRelationsToStorage() {
    try {
        localStorage.setItem('relations', JSON.stringify(relations.value));
        console.log('已保存', relations.value.length, '个关系到本地存储');
    } catch (error) {
        console.error('保存关系到本地存储失败:', error);
    }
}

// 触发文件上传
function triggerFileUpload() {
    fileInput.value.click();
}

// 编辑关系
function editRelation(relation) {
    currentRelation.value = { ...relation };
    dialogVisible.value = true;
}

// 保存关系
function saveRelation() {
    // 验证必填字段
    if (!currentRelation.value.id || !currentRelation.value.text || !currentRelation.value.source || !currentRelation.value.target) {
        ElMessage.error('请填写所有必填字段');
        return;
    }

    // 查找源实体和目标实体的文本
    const sourceEntity = entities.value.find(entity => entity.id === currentRelation.value.source);
    const targetEntity = entities.value.find(entity => entity.id === currentRelation.value.target);

    // 更新sourceText和targetText
    currentRelation.value.sourceText = sourceEntity ? sourceEntity.text : '未找到实体';
    currentRelation.value.targetText = targetEntity ? targetEntity.text : '未找到实体';

    const index = relations.value.findIndex(r => r.id === currentRelation.value.id);
    if (index !== -1) {
        relations.value[index] = { ...currentRelation.value };
        dialogVisible.value = false;
        // 更新全局关系列表，供TinyMCE编辑器使用
        window.relations = relations.value;
        // 保存更新后的关系数据到本地存储
        saveRelationsToStorage();
        ElMessage.success('关系更新成功');
    }
}

// 删除关系
function deleteRelation(relation) {
    relationToDelete.value = relation;
    deleteDialogVisible.value = true;
}

// 确认删除关系
function confirmDelete() {
    if (relationToDelete.value) {
        const index = relations.value.findIndex(r => r.id === relationToDelete.value.id);
        if (index !== -1) {
            relations.value.splice(index, 1);
            // 更新全局关系列表，供TinyMCE编辑器使用
            window.relations = relations.value;
            // 保存更新后的关系数据到本地存储
            saveRelationsToStorage();
            ElMessage.success('关系删除成功');
        }
        deleteDialogVisible.value = false;
        relationToDelete.value = null;
    }
}

// 显示添加关系对话框
function showAddRelationDialog() {
    addRelationDialogVisible.value = true;
}

// 处理添加关系
function handleAddRelation(relation) {
    // 添加新关系到关系列表
    relations.value.push({
        ...relation,
        markedCount: 0,
        annotatedTexts: [],
        checkedStatus: []
    });

    // 更新全局关系列表，供TinyMCE编辑器使用
    window.relations = relations.value;
    // 保存更新后的关系数据到本地存储
    saveRelationsToStorage();
    ElMessage.success('关系添加成功');
}

// 导出关系定义
function exportDefinition() {
    if (relations.value.length === 0) {
        ElMessage.error('没有可导出的关系数据');
        return;
    }

    // 准备导出数据
    const exportData = relations.value.map(relation => ({
        id: relation.id,
        text: relation.text,
        source: relation.source,
        target: relation.target,
        description: relation.description,
        path: relation.path
    }));

    // 创建工作簿和工作表
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.json_to_sheet(exportData);
    XLSX.utils.book_append_sheet(wb, ws, '关系定义');

    // 生成Excel文件并下载
    const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '关系定义.xlsx');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success('导出成功');
}

// 处理文件上传
function handleFileUpload(event) {
    const file = event.target.files[0];
    if (!file) {
        ElMessage.error('请选择文件');
        return;
    }

    // 验证文件类型
    if (!file.name.endsWith('.xlsx')) {
        ElMessage.error('请上传.xlsx格式的文件');
        return;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
        try {
            const data = new Uint8Array(e.target.result);
            const workbook = XLSX.read(data, { type: 'array' });

            if (workbook.SheetNames.length === 0) {
                throw new Error('Excel文件中没有工作表');
            }

            const firstSheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[firstSheetName];
            const jsonData = XLSX.utils.sheet_to_json(worksheet);

            if (jsonData.length === 0) {
                throw new Error('Excel文件中没有数据');
            }

            // 验证数据格式
            const validData = jsonData.filter(row => {
                const hasRequiredFields = row['id'] && row['text'] && row['source'] && row['target'] && row['description'] && row['path'];
                return hasRequiredFields;
            });

            if (validData.length === 0) {
                throw new Error('没有找到有效的关系数据，请确保Excel中包含必要的字段');
            }

            // 获取实体数据，用于关联source和target
            let entityData = [];
            try {
                const storedEntities = localStorage.getItem('entities');
                if (storedEntities) {
                    entityData = JSON.parse(storedEntities);
                    console.log('从本地存储加载了', entityData.length, '个实体用于关系映射');
                }
            } catch (error) {
                console.error('从本地存储加载实体失败:', error);
            }

            // 转换数据格式并添加随机背景色
            const getRandomPastelColor = () => {
                const hue = Math.floor(Math.random() * 360);
                return `hsl(${hue}, 90%, 70%)`;
            };

            relations.value = validData.map(row => {
                // 查找source和target对应的实体
                const sourceEntity = entityData.find(entity => entity.id === row['source']);
                const targetEntity = entityData.find(entity => entity.id === row['target']);

                return {
                    id: row['id'],
                    text: row['text'],
                    source: row['source'],
                    target: row['target'],
                    sourceText: sourceEntity ? sourceEntity.text : '未找到实体',
                    markedCount: 0, // 初始化标注计数为0
                    targetText: targetEntity ? targetEntity.text : '未找到实体',
                    description: row['description'],
                    path: row['path'],
                    style: { 'background-color': getRandomPastelColor() }
                };
            });

            // 保存导入的关系数据到本地存储
            saveRelationsToStorage();
            ElMessage.success(`成功导入 ${relations.value.length} 个关系`);
            // 清空文件输入，以便下次选择同一文件时也能触发change事件
            event.target.value = '';
        } catch (error) {
            console.error('文件解析错误:', error);
            ElMessage.error(error.message || '文件解析失败，请检查文件格式');
        }
    };

    reader.onerror = () => {
        ElMessage.error('文件读取失败');
    };

    reader.readAsArrayBuffer(file);
}

// 监听localStorage中的关系数据变化
watch(() => localStorage.getItem('relationsData'), (newData) => {
    if (newData) {
        try {
            const parsedData = JSON.parse(newData);
            updateRelationInstances(parsedData);
        } catch (error) {
            console.error('解析关系数据失败:', error);
        }
    }
});

// 更新关系实例列表
const updateRelationInstances = (relationsData) => {
    if (!Array.isArray(relationsData)) {
        console.error('关系数据不是数组:', relationsData);
        return;
    }

    relationInstances.value = relationsData.map(relation => {
        // 确保relation对象及其属性存在
        if (!relation || !relation.sourceEntity || !relation.targetEntity || !relation.relation) {
            console.warn('关系数据格式不正确:', relation);
            return null;
        }

        // 查找对应的关系类以获取其背景颜色
        const relationClass = relations.value.find(r => r.id === relation.relation.id);
        const style = relationClass && relationClass.style ? relationClass.style : { 'background-color': '#f0f0f0' };

        return {
            sourceId: relation.sourceEntity.id,
            targetId: relation.targetEntity.id,
            relationId: relation.relation.id,
            sourceText: relation.sourceEntity.text || '未知实体',
            relationText: relation.relation.text || '未知关系',
            targetText: relation.targetEntity.text || '未知实体',
            style: style // 使用关系类的样式，如果没有则使用默认样式
        };
    }).filter(item => item !== null); // 过滤掉无效的项
};
</script>
